
const db = require('db');
const fs = require('fs')
const process = require("child_process");
const path = require('path');
const moment = require('moment');
const { encode } = require('js-base64');
const { v4 } = require('uuid');
const { toUpdate } = require('tools/sqlString');
const log = require('tools/log');

module.exports = async ctx => {
    const { connection, run } = db.init();
    await run('BEGIN'); // 开始事务
    try {
        const id = ctx.params.id;
        const fv4 = v4();
        await update(id, ctx, fv4, run);
        await rename(ctx, fv4);
        await run('COMMIT');
        ctx.status = 200;
        ctx.body = 'ok';
    } catch (error) {
        await run('ROLLBACK');
        ctx.status = 500;
        ctx.body = error
        log('---------------------------------------------------')
        console.log(error)
    }
    await execSync(`rm ${ctx.request.body.filePath}`);
    connection.end();
}

async function update(id, ctx, fv4, run) {

    const body = { ...ctx.request.body }
    const settlementDetails = body.fileName && encode(path.join(getNewPath(fv4), body.fileName));
    if (settlementDetails && ctx.request.body.filePath) {
        body.settlementDetails = settlementDetails;
        delete body.filePath;
        delete body.fileName;
    }else{
        delete body.filePath;
        delete body.fileName;
        delete body.settlementDetails;
    }

    const sql = `
        UPDATE settlement SET ${toUpdate(body)}
        WHERE id = ${id}
    `;

    const result = await run(sql);
    if (result.err) {
        throw result.err
    }
}

/** 获取一个新路径 */
function getNewPath(fv4) {
    return path.join(moment().format('YYYY_MM'), 'settlement', fv4);
}

/** 移动结算明细文件 */
async function rename(ctx, fv4) {
    try {
        const fileName = ctx.request.body.fileName;
        const filePath = ctx.request.body.filePath;
        if (!fileName || !filePath) return;

        const files = '../../../../../../files';
        const newPath = getNewPath(fv4);
        await execSync(`mkdir -p ${path.join(__dirname, files, newPath)}`);
        fs.renameSync(filePath, path.join(__dirname, files, newPath, fileName))
    } catch (error) {
        log('---------------------------------------------------')
        console.log(error)
    }
}

/** 执行 sh 脚本 */
function execSync(command) {
    return new Promise(resolve => {
        process.exec(command, resolve)
    })
}